package com.ysxsoft.wdg.ui.fragment;

import android.content.Intent;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.classic.common.MultipleStatusView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.adapter.center_st.StShopAdapter;
import com.ysxsoft.wdg.base.BaseFragment;
import com.ysxsoft.wdg.base.BaseGWebViewActivity;
import com.ysxsoft.wdg.bean.BannerBean;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.response.TopAdResponse;
import com.ysxsoft.wdg.bean.event.CommentEvent;
import com.ysxsoft.wdg.bean.st.StHomeBean;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.ui.activity.MainActivity;
import com.ysxsoft.wdg.ui.activity.center_st.StShopDetailActivity;
import com.ysxsoft.wdg.ui.activity.center_st.ShopFjActivity;
import com.ysxsoft.wdg.ui.activity.center_st.StCateListActivity;
import com.ysxsoft.wdg.ui.activity.center_st.StSearchActivity;
import com.ysxsoft.wdg.ui.activity.center_zy.GoodsDetailActivity;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.view.CategoryViewPager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;

import static com.ysxsoft.wdg.bean.event.CommentEvent.EventStatus.LOCATION_UP;

public class StFragment extends BaseFragment implements OnRefreshListener {

    @BindView(R.id.iv_ms)
    ImageView ivMs;
    @BindView(R.id.iv_new)
    ImageView ivNew;
    @BindView(R.id.iv_find)
    ImageView ivFind;
    @BindView(R.id.iv_gg)
    ImageView ivGg;
    @BindView(R.id.tv_near)
    TextView tvNear;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;
    private String id1, id2, id3, content4;
    @BindView(R.id.categoryViewPager)
    CategoryViewPager categoryViewPager;

    private TextView[] tvs;
    private ImageView[] ivs;
    private StShopAdapter mAdapter;

    private String lng = "", lat = "", address = "";
    private List<BannerBean> cateList = new ArrayList<>();


    @Override
    protected int getLayoutId() {
        return R.layout.fm_st;
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);

        //TODO 取消屏蔽
        lng = SharePrefUtils.getLongitude();
        lat = SharePrefUtils.getLatitude();
        address = SharePrefUtils.getAddress();

        ivMs.setImageResource(R.mipmap.st_ms);
        ivNew.setImageResource(R.mipmap.st_new);
        ivFind.setImageResource(R.mipmap.st_find);

        recyclerview.setFocusable(false);
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        mAdapter = new StShopAdapter(R.layout.item_shop);
        recyclerview.setAdapter(mAdapter);

        onRefresh(refreshLayout);

//        getTopAd();
//        getBottomAd();
    }


    @Override
    protected void setListener() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setEnableLoadmore(false);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                StShopDetailActivity.start(mContext, mAdapter.getItem(position).getId());
            }
        });
    }


    @OnClick({R.id.rl_search, R.id.tv_near})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_search:
                startActivity(new Intent(mContext, StSearchActivity.class));
                break;
            case R.id.tv_near://附近商家
                ShopFjActivity.start(mContext);
                break;
        }
    }

    private void toStCateListActivity(int i) {
        StCateListActivity.start(mContext, cateList.get(i).getId(), cateList.get(i).getName());
    }

    @OnClick({R.id.iv_ms, R.id.iv_new, R.id.iv_find, R.id.iv_gg})
    public void onViewClicked2(View view) {
        switch (view.getId()) {
            case R.id.iv_ms://限时秒杀
                GoodsDetailActivity.start(getActivity(), id1);
                break;
            case R.id.iv_new://新品好货
                GoodsDetailActivity.start(getActivity(), id2);
                break;
            case R.id.iv_find://发现好货
                GoodsDetailActivity.start(getActivity(), id3);
                break;
            case R.id.iv_gg://广告
//              BaseGWebViewActivity.start(getActivity(),"广告",content4);
                MainActivity activity = (MainActivity) getActivity();
                activity.showMPage();
                break;
        }
    }


    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.finishRefresh(500);
        mAdapter.clear();
        getList();

        getTopAd();
        getBottomAd();
    }


    private void getList() {
        mApiHelper.getStHome(address, lng, lat, new Observer<BaseBean<StHomeBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<StHomeBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    StHomeBean data = baseBean.getData();
                    cateList = data.getCate();
                    initCategory(cateList);
                    if(data.getCompany()!=null&&data.getCompany().size()>=5){
                        mAdapter.setFooterView(createFooterView());
                    }else{
                        mAdapter.removeAllFooterView();
                    }
                    mAdapter.setNewData(data.getCompany());
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private View createFooterView(){
        View view=View.inflate(getActivity(),R.layout.footer_st,null);
        TextView lookMore=view.findViewById(R.id.lookMore);
        lookMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShopFjActivity.start(mContext);
            }
        });
        return view;
    }

    @Subscribe
    public void getEvent(CommentEvent event) {

        int code = event.getCode();
        if (code == LOCATION_UP) {

            lng = SharePrefUtils.getLongitude();
            lat = SharePrefUtils.getLatitude();
            address = SharePrefUtils.getAddress();

            onRefresh(refreshLayout);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    /**
     * 获取顶部广告
     */
    private void getTopAd() {
        OkHttpUtils.post()
                .url(UrlHost.MAIN_AD)
                .addParams("type", "0")//0：上边3个是   1：下边1个
                .addParams("style", "2")    //1首页3自营2实体
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    TopAdResponse messageBean = JsonUtils.parseByGson(response, TopAdResponse.class);
                    if (messageBean == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(messageBean.getCode())) {
                        List<TopAdResponse.DataBean> list = messageBean.getData();
                        if (list.size() == 3) {
                            Glide.with(getActivity()).load(list.get(0).getPic()).into(ivMs);
                            Glide.with(getActivity()).load(list.get(1).getPic()).into(ivNew);
                            Glide.with(getActivity()).load(list.get(2).getPic()).into(ivFind);
                            id1 = "" + list.get(0).getGoodsid();
                            id2 = "" + list.get(1).getGoodsid();
                            id3 = "" + list.get(2).getGoodsid();
                        }
                    }
                } else {
                }
            }
        });
    }

    /**
     * 获取顶部广告
     */
    private void getBottomAd() {
        OkHttpUtils.post()
                .url(UrlHost.MAIN_AD)
                .addParams("type", "1")//0：上边3个是   1：下边1个
                .addParams("style", "2")    //1首页3自营2实体
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    TopAdResponse messageBean = JsonUtils.parseByGson(response, TopAdResponse.class);
                    if (messageBean == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(messageBean.getCode())) {
                        List<TopAdResponse.DataBean> list = messageBean.getData();
                        if (list.size() == 1) {
                            Glide.with(getActivity()).load(list.get(0).getPic()).into(ivGg);
                            content4 = list.get(0).getContent();
                        }
                    }
                } else {
                }
            }
        });
    }

    private void initCategory(List<BannerBean> menus) {
        if (menus == null) {
            return;
        }
        List<CategoryViewPager.Item> list = new ArrayList<>();
        for (int i = 0; i <menus.size(); i++) {
            CategoryViewPager.Item item=new CategoryViewPager.Item(menus.get(i).getId(),menus.get(i).getPic(),menus.get(i).getName());
            list.add(item);
        }
        categoryViewPager.setData(list);
        categoryViewPager.setListener(new CategoryViewPager.OnMenuClickListener() {
            @Override
            public void OnMenuClick(String id, String name, int position) {
//                toStCateListActivity(position);
                StCateListActivity.start(mContext, id,name);
            }
        });
    }

}
